<template>
  <view class="container">
    <tui-search-box placeholder="书名、作者、关键字" @search="search" />
    <view class="tui-flex tui-line-feed">
      <view
        v-for="(item, index) in bookshelfs"
        :key="index"
        class="story-item"
        hover-class="tui-white-hover"
        @tap="read(index)"
        @longpress="operate(index)"
      >
        <view class="story-cover">
          <image mode="widthFix" :src="item.cover" class="story-image" />
          <tui-badge class="story-badge" type="red" :visible="item.hasNew" size="small">新</tui-badge>
          <view
            v-if="item.loading"
            style="position: absolute;top: 0;bottom: 0;left: 0;right: 0;background-color: #aaa;opacity: 0.9;"
          >
            <tui-loadmore
              visible
              :index="3"
              type="primary"
              text=" "
              style="position: absolute;top: 60rpx;bottom: 0;left: 0;right: 0;"
            ></tui-loadmore>
          </view>
        </view>
        <text class="story-name">{{ item.name }}</text>
      </view>
      <view class="story-item" hover-class="tui-white-hover">
        <tui-upload-add @add="search" />
      </view>
    </view>
    <tui-modal
      :show="removeConfirm"
      @click="handleRemove"
      @cancel="hideConfirm"
      :content="'确定删除《' + bookshelfs[removeIndex].name + '》吗？'"
      color="#333"
      :size="32"
      :button="confirmButtons"
    ></tui-modal>
    <tui-page-loading type="slide" :show="loading" />
  </view>
</template>

<script>
import tuiSearchBox from "@/components/search-box/search-box.vue";
import tuiUploadAdd from "@/components/upload-add/upload-add.vue";
import tuiBadge from "@/components/badge/badge.vue";
import tuiPageLoading from "@/components/page-loading/page-loading.vue";
import tuiModal from "@/components/modal/modal";
import tuiLoadmore from "@/components/loadmore/loadmore";
import navigateTo from "@/pages/read/navigateTo.js";
import { mapActions, mapState, mapMutations } from "vuex";
import { stringify } from "qs";

export default {
  components: {
    tuiSearchBox,
    tuiUploadAdd,
    tuiBadge,
    tuiPageLoading,
    tuiModal,
    tuiLoadmore
  },
  data() {
    return {
      loading: false,
      removeConfirm: false,
      removeIndex: 0,
      confirmButtons: [
        {
          text: "取消",
          type: "gray"
        },
        {
          text: "确定",
          type: "danger"
        }
      ]
    };
  },
  computed: {
    ...mapState(["openid", "bookshelfs"])
  },
  onLoad() {
    this.loading = true;
    this.init();
  },
  onPullDownRefresh: function() {
    this.init(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    ...mapActions(["login"]),
    ...mapMutations(["setBookshelfs"]),
    init(callback) {
      this.db
        .collection("bookshelfs")
        .where({
          _openid: this.openid
        })
        .orderBy("read_time", "desc")
        .get()
        .then(res => {
          // console.log(res);
          if (res.errMsg == "collection.get:ok") {
            res.data.forEach(item => {
              item.loading = false;
            });
            this.setBookshelfs(res.data);
            this.checkUpdate();
          } else {
            this.tui.toast(res.errMsg);
          }
          this.loading = false;
          callback && callback();
        })
        .catch(err => {
          console.log(err);
          this.tui.toast("发生错误了");
          this.loading = false;
        });
    },
    // 检查是否有更新
    checkUpdate() {
      this.bookshelfs.forEach((book, index) => {
        if (!book.hasNew) {
          this.setBook(index, {
            loading: true
          });
          this.callFunc({
            name: "bookDetail",
            data: {
              source_id: book.source_id,
              read_url: book.read_url
            }
          })
            .then(res => {
              // console.log(book, res);
              if (
                res.result &&
                res.result.errMsg == "ok" &&
                res.result.data &&
                res.result.data.latest_chapter_url
              ) {
                if (
                  res.result.data.latest_chapter_url != book.latest_chapter_url
                ) {
                  this.db
                    .collection("bookshelfs")
                    .doc(book._id)
                    .update({
                      data: {
                        hasNew: true,
                        latest_chapter_url: res.result.data.latest_chapter_url
                      }
                    })
                    .then(r => {
                      if (r.errMsg == "document.update:ok") {
                        this.setBook(index, {
                          hasNew: true,
                          latest_chapter_url: res.result.data.latest_chapter_url
                        });
                      }
                    })
                    .catch(err => {
                      console.log(err);
                    });
                }
              }
              this.setBook(index, {
                loading: false
              });
            })
            .catch(err => {
              console.log(book, "检查更新时出错", err);
              this.setBook(index, {
                loading: false
              });
            });
        }
      });
    },
    setBook(index, book) {
      const bookshelfs = this.bookshelfs;
      for (const key in book) {
        bookshelfs[index][key] = book[key];
      }
      this.setBookshelfs(bookshelfs);
    },
    // 导航到搜索页面
    search: function() {
      uni.navigateTo({
        url: "/pages/search/search"
      });
    },
    read(index) {
      const { _id } = this.bookshelfs[index];
      navigateTo("pages/read/read", { _id });
    },
    operate(index) {
      const { source_id, read_url, _id, url } = this.bookshelfs[index];
      uni.showActionSheet({
        itemList: ["书籍详情", "书籍目录", "从书架移除"],
        success: res => {
          switch (res.tapIndex) {
            case 0:
              uni.navigateTo({
                url:
                  "/pages/detail/detail?" +
                  stringify({ source_id, read_url }, { encode: false })
              });
              break;
            case 1:
              uni.navigateTo({
                url:
                  "/pages/catalog/catalog?" +
                  stringify({ source_id, read_url, _id, url })
              });
              break;
            case 2:
              this.removeConfirm = true;
              this.removeIndex = index;
              break;
            default:
              break;
          }
        }
      });
    },
    hideConfirm() {
      this.removeConfirm = false;
    },
    handleRemove(e) {
      const index = e.index;
      if (index == 0) {
        this.removeConfirm = false;
      } else if (index == 1) {
        // 请求删除
        uni.showLoading({ title: "加载中" });
        this.db
          .collection("bookshelfs")
          .doc(this.bookshelfs[this.removeIndex]._id)
          .remove()
          .then(res => {
            uni.hideLoading();
            if (res.errMsg == "document.remove:ok") {
              const bookshelfs = this.bookshelfs;
              bookshelfs.splice(this.removeIndex, 1);
              this.setBookshelfs(bookshelfs);
            } else {
              this.tui.toast(res.errMsg);
            }
            this.removeConfirm = false;
          })
          .catch(err => {
            uni.hideLoading();
            this.tui.toast("删除失败");
          });
      }
    }
  }
};
</script>

<style>
.story-item {
  width: 200rpx;
  padding: 10rpx 20rpx;
  text-align: center;
  min-height: 255rpx;
}
.story-cover {
  position: relative;
  margin: 0 auto;
  width: 80%;
}
.story-image {
  width: 100%;
  max-height: 234rpx;
}
.story-badge {
  position: absolute;
  right: -7rpx;
  top: -7rpx;
}
.story-name {
  font-size: 28rpx;
}
</style>
